package com.cirkana.viewer.security;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.cirkana.CirkanaActivity;
import com.cirkana.serial.SerializationException;
import com.cirkana.viewer.R;
import com.cirkana.viewer.security.model.SecurityController;

public class SignInActivity extends CirkanaActivity {

	public static final int RESULT_SIGNIN_OK = 0;

	private Button signinButton;
	private EditText userEditText;
	private EditText passwordEditText;

	private SignInPassData passData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.signin);

		this.signinButton = ((Button) findViewById(R.id.login_signin));
		this.userEditText = ((EditText) findViewById(R.id.user));
		this.passwordEditText = ((EditText) findViewById(R.id.password));

		this.passData = (SignInPassData) getRequest(SignInPassData.class);
		if (this.passData.hasProfile()) {
			this.userEditText.setText(this.passData.getProfile().getCirkanaCredential().getUser());
		}

		this.signinButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				signIn();
			}
		});

	}

	protected void signIn() {
		String user = userEditText.getText().toString();
		String password = passwordEditText.getText().toString();
		SignInPassData result = new SignInPassData();
		result.setProfile(SecurityController.createProfile(user, password));
		try {
			setResponse(RESULT_SIGNIN_OK, result);
		} catch (SerializationException e) {
			showErrorMessage(e);
		}
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			signIn();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
